package com.zyh.flink.day03;

import org.apache.flink.api.common.functions.*;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class ReducingStateTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> hadoop10 = environment.socketTextStream("hadoop10", 9999);
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = hadoop10.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String s, Collector<String> collector) throws Exception {
                String[] words = s.split("\\s+");
                for (String word : words) {
                    collector.collect(word);
                }
            }
        }).map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                return Tuple2.of(s,1);
            }
        }).keyBy(t -> t.f0);

        SingleOutputStreamOperator<Tuple2<String, Integer>> reducingStateStream = keyedStream.map(new MyReducingStateRichMapFunction());
        reducingStateStream.print();

        environment.execute("ReducingStateJob");

    }
}
class MyReducingStateRichMapFunction extends RichMapFunction<Tuple2<String,Integer>,Tuple2<String,Integer>>{
    private ReducingState<Integer> reducingState;

    @Override
    public void open(Configuration parameters) throws Exception {
        RuntimeContext ctx = getRuntimeContext();
//        ReduceFunction<Integer> reduceFunction = new ReduceFunction<Integer>() {
//            @Override
//            public Integer reduce(Integer value1, Integer value2) throws Exception {
//                return value1 + value2;
//            }
//        };
        ReducingStateDescriptor<Integer> rsd = new ReducingStateDescriptor<Integer>("wordcount",(v1,v2)->v1+v2, Types.INT);
        this.reducingState = ctx.getReducingState(rsd);
    }

    @Override
    public Tuple2<String, Integer> map(Tuple2<String, Integer> value) throws Exception {
        //使用reducingState
        //每来一个元素,向reducingState添加
        this.reducingState.add(1);
        Integer count = this.reducingState.get();

        return Tuple2.of(value.f0, count);
    }
}